package com.yy.young.log.core;

import com.yy.young.interfaces.log.service.ILogHandler;
import com.yy.young.log.handler.DefaultLogHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Map;

/**
 * 日志处理器工厂
 * 提供自定义日志处理器注册服务,并根据注册名称产出对应的日志处理器实例
 * Created by rookie on 2017/11/10.
 */
public class LogHandlerFactory {

    private static final Logger logger = LoggerFactory.getLogger(LogHandlerFactory.class);
    /**
     * 日志处理器池
     */
    private static Map<String, ILogHandler> handlerPool;
    /**
     * 默认处理器
     */
    private static ILogHandler defaultHandler;

    /**
     * 根据处理器名称获取处理器
     * @param handlerName
     * @return
     */
    public static ILogHandler getHandler(String handlerName){
        return handlerPool.get(handlerName);
    }

    @PostConstruct
    public void init() {
        logger.info("[日志处理器工厂] 初始化开始...");
        for(Map.Entry<String, ILogHandler> entry : handlerPool.entrySet()){
            logger.info("[日志处理器工厂] 日志处理器{}已注册!", entry.getKey());
        }
        if (defaultHandler == null){
            logger.warn("[日志处理器工厂] 默认日志处理器无效,new一个DefaultLogHandler!");
            defaultHandler = new DefaultLogHandler();
        }
        logger.info("[日志处理器工厂] 初始化结束!");
    }

    public static Map<String, ILogHandler> getHandlerPool() {
        return handlerPool;
    }

    public static void setHandlerPool(Map<String, ILogHandler> handlerPool) {
        LogHandlerFactory.handlerPool = handlerPool;
    }

    public static ILogHandler getDefaultHandler() {
        return defaultHandler;
    }

    public static void setDefaultHandler(ILogHandler defaultHandler) {
        LogHandlerFactory.defaultHandler = defaultHandler;
    }
}
